Skip to content

Conversation

capcom6
Copy link
Owner

@capcom6 capcom6 commented Jul 22, 2025

Summary by CodeRabbit

  • New Features
    • Introduced a foreground service to maintain a persistent connection with server-sent events (SSE), ensuring real-time updates.
    • Added an SSE manager to handle SSE connections, event callbacks, and reconnection logic.
    • Added event routing to centralize handling of external events and trigger appropriate internal actions.
    • Added new event types and corresponding workers for message enqueueing, webhook updates, settings updates, and message export requests.
    • Introduced a receiver service to process message export requests asynchronously.
  • Enhancements
    • Updated app configuration to include OkHttp SSE dependencies.
    • Integrated SSE service lifecycle management with existing gateway operations.
    • Simplified push message handling by delegating event processing to the centralized event router.
    • Added persistent notification and resource string for SSE foreground service status.
    • Improved logging and error handling for event processing.
    • Updated notification service with new icon for real-time events.
    • Added management of FCM token within gateway settings for improved device registration handling.
    • Removed deprecated push event and payload classes; streamlined event naming and package structure.
    • Reordered string resources for better readability and maintenance.
    • Removed FCM token management from settings helper to centralize in gateway settings.

Copy link

coderabbitai bot commented Jul 22, 2025

Walkthrough

The changes introduce Server-Sent Events (SSE) support to the Android app. This includes adding OkHttp SSE dependencies, a new SSEManager helper class for managing SSE connections, a new SSEForegroundService Android service for persistent SSE listening, and updates to the manifest and gateway service to integrate and manage this new foreground service. Additionally, event routing and handling were refactored and extended with new event classes, updated event receivers, and integration of a centralized EventsRouter. Some deprecated event classes and payloads were removed, and the PushService was refactored to delegate event handling to the new router.

Changes

Cohort / File(s) Change Summary
Build Configuration
app/build.gradle
Added OkHttp and OkHttp SSE dependencies with a version variable.
Android Manifest
app/src/main/AndroidManifest.xml
Added SSEForegroundService declaration; reordered some service attributes.
SSE Management Helper
app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt
New class managing SSE connections using OkHttp with reconnection logic and event callbacks.
Foreground Service Implementation
app/src/main/java/me/capcom/smsgateway/modules/gateway/services/SSEForegroundService.kt
New Android foreground service maintaining persistent SSE connection with wake and Wi-Fi locks.
Gateway Service Integration
app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewayService.kt
Modified to start and stop SSEForegroundService in its lifecycle methods; updated push token handling.
Event Classes Added
app/src/main/java/me/capcom/smsgateway/modules/gateway/events/MessageEnqueuedEvent.kt, .../SettingsUpdatedEvent.kt, .../WebhooksUpdatedEvent.kt, app/src/main/java/me/capcom/smsgateway/modules/receiver/events/MessagesExportRequestedEvent.kt
Added new event classes extending AppEvent for gateway and receiver modules with event name constants and payload handling.
Event Classes Removed
app/src/main/java/me/capcom/smsgateway/modules/push/events/PushMessageEnqueuedEvent.kt, app/src/main/java/me/capcom/smsgateway/modules/push/payloads/MessagesExportRequestedPayload.kt
Removed deprecated event and payload classes related to push events.
Event Routing and Handling
app/src/main/java/me/capcom/smsgateway/modules/orchestrator/EventsRouter.kt, .../Module.kt, .../OrchestratorService.kt
Added EventsRouter for mapping external events to internal events; updated orchestrator module and service to include receiver service and router.
Event Receivers and Services
app/src/main/java/me/capcom/smsgateway/modules/receiver/EventsReceiver.kt, .../ReceiverService.kt
Added new receiver class and service methods to start/stop event collection and processing.
Gateway Workers
app/src/main/java/me/capcom/smsgateway/modules/gateway/workers/WebhooksUpdateWorker.kt
Renamed worker constant from "CloudUpdateWorker" to "WebhooksUpdateWorker" for consistency.
EventsReceiver Update
app/src/main/java/me/capcom/smsgateway/modules/gateway/EventsReceiver.kt
Replaced PushMessageEnqueuedEvent with MessageEnqueuedEvent; added collectors for WebhooksUpdatedEvent, SettingsUpdatedEvent, and DeviceRegisteredEvent triggering corresponding workers and services.
PushService Refactor
app/src/main/java/me/capcom/smsgateway/services/PushService.kt
Refactored to remove coroutine event handling and direct worker calls; delegates event processing to EventsRouter. Removed related imports and coroutine scope.
Notifications Update
app/src/main/java/me/capcom/smsgateway/modules/notifications/NotificationsService.kt
Added new notification ID and icon mapping for real-time events notification.
Resource Strings
app/src/main/res/values/strings.xml
Added string resource for "Listening to the server events..." notification text.
Settings and Gateway Settings Update
app/src/main/java/me/capcom/smsgateway/helpers/SettingsHelper.kt, app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewaySettings.kt
Removed fcmToken property from SettingsHelper; added fcmToken property to GatewaySettings with storage backing.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant GatewayService
    participant SSEForegroundService
    participant SSEManager
    participant Server

    App->>GatewayService: start(context)
    GatewayService->>SSEForegroundService: start(context)
    SSEForegroundService->>SSEManager: connect()
    SSEManager->>Server: Establish SSE connection
    Server-->>SSEManager: Send event(s)
    SSEManager-->>SSEForegroundService: onEvent callback
    SSEForegroundService-->>GatewayService: (optional event handling)
    App->>GatewayService: stop(context)
    GatewayService->>SSEForegroundService: stop(context)
    SSEForegroundService->>SSEManager: disconnect()
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~40 minutes


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4c326ad and 0a94d1e.

⛔ Files ignored due to path filters (5)
  • app/src/main/res/drawable-hdpi/notif_realtime_events.png is excluded by !**/*.png
  • app/src/main/res/drawable-mdpi/notif_realtime_events.png is excluded by !**/*.png
  • app/src/main/res/drawable-xhdpi/notif_realtime_events.png is excluded by !**/*.png
  • app/src/main/res/drawable-xxhdpi/notif_realtime_events.png is excluded by !**/*.png
  • app/src/main/res/drawable-xxxhdpi/notif_realtime_events.png is excluded by !**/*.png
📒 Files selected for processing (25)
  • app/build.gradle (2 hunks)
  • app/src/main/AndroidManifest.xml (2 hunks)
  • app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/helpers/SettingsHelper.kt (0 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEventType.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/EventsReceiver.kt (3 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewayService.kt (5 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewaySettings.kt (2 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/MessageEnqueuedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/SettingsUpdatedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/WebhooksUpdatedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/services/SSEForegroundService.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/workers/WebhooksUpdateWorker.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/notifications/NotificationsService.kt (2 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/orchestrator/EventsRouter.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/orchestrator/Module.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/orchestrator/OrchestratorService.kt (3 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/push/events/PushMessageEnqueuedEvent.kt (0 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/push/payloads/MessagesExportRequestedPayload.kt (0 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/receiver/EventsReceiver.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/receiver/ReceiverService.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/receiver/events/MessagesExportRequestedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/services/PushService.kt (3 hunks)
  • app/src/main/res/values/strings.xml (5 hunks)
💤 Files with no reviewable changes (3)
  • app/src/main/java/me/capcom/smsgateway/helpers/SettingsHelper.kt
  • app/src/main/java/me/capcom/smsgateway/modules/push/events/PushMessageEnqueuedEvent.kt
  • app/src/main/java/me/capcom/smsgateway/modules/push/payloads/MessagesExportRequestedPayload.kt
✅ Files skipped from review due to trivial changes (1)
  • app/src/main/res/values/strings.xml
🚧 Files skipped from review as they are similar to previous changes (21)
  • app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEvent.kt
  • app/build.gradle
  • app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEventType.kt
  • app/src/main/java/me/capcom/smsgateway/modules/orchestrator/Module.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/SettingsUpdatedEvent.kt
  • app/src/main/java/me/capcom/smsgateway/modules/notifications/NotificationsService.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewaySettings.kt
  • app/src/main/java/me/capcom/smsgateway/modules/receiver/ReceiverService.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/MessageEnqueuedEvent.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/WebhooksUpdatedEvent.kt
  • app/src/main/AndroidManifest.xml
  • app/src/main/java/me/capcom/smsgateway/modules/orchestrator/EventsRouter.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/EventsReceiver.kt
  • app/src/main/java/me/capcom/smsgateway/modules/orchestrator/OrchestratorService.kt
  • app/src/main/java/me/capcom/smsgateway/services/PushService.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/workers/WebhooksUpdateWorker.kt
  • app/src/main/java/me/capcom/smsgateway/modules/receiver/EventsReceiver.kt
  • app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewayService.kt
  • app/src/main/java/me/capcom/smsgateway/modules/receiver/events/MessagesExportRequestedEvent.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/services/SSEForegroundService.kt
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/sse-events

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (1)
app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt (1)

20-23: Consider making timeout configurable and improve scope management.

The hardcoded 30-second timeout might need to be configurable for different use cases. Also, consider using SupervisorJob() for better error isolation.

-    private val client = OkHttpClient.Builder()
-        .readTimeout(30, TimeUnit.SECONDS)
-        .build()
-    private val scope = CoroutineScope(Dispatchers.IO + Job())
+    private val client = OkHttpClient.Builder()
+        .readTimeout(30, TimeUnit.SECONDS)
+        .build()
+    private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 404dd29 and 430f8f9.

📒 Files selected for processing (5)
  • app/build.gradle (2 hunks)
  • app/src/main/AndroidManifest.xml (2 hunks)
  • app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewayService.kt (2 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/services/SSEForegroundService.kt (1 hunks)
🔇 Additional comments (8)
app/build.gradle (2)

60-60: LGTM! Version variable properly defined.

The OkHttp version variable is well-structured and follows the existing pattern.


84-85: OkHttp 4.10.0 & SSE added – no known CVEs found
Verified via OSS Index for pkg:maven/com.squareup.okhttp3/okhttp@4.10.0: no reported vulnerabilities. Please confirm this version is compatible with your project’s Android API levels (minSdk/targetSdk).

• app/build.gradle (lines 84-85):

implementation("com.squareup.okhttp3:okhttp:$okhttp_version")
implementation("com.squareup.okhttp3:okhttp-sse:$okhttp_version")
app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewayService.kt (3)

12-12: LGTM! Import properly added.

The SSEForegroundService import follows the existing import pattern.


49-49: Good placement of SSE service startup.

The SSE service is properly started after other workers, which ensures dependencies are initialized first.


57-57: Excellent service shutdown ordering.

The SSE service is stopped before other workers, which is the correct order to prevent connection issues during shutdown.

app/src/main/java/me/capcom/smsgateway/modules/gateway/services/SSEForegroundService.kt (1)

79-93: Excellent service lifecycle management.

The companion object methods properly handle Android API differences for starting foreground services and provide clean start/stop functionality.

app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt (2)

34-82: Excellent SSE connection implementation.

The connection logic properly handles authentication, event callbacks, and error scenarios. The event listener implementation covers all necessary cases.


92-105: Well-implemented reconnection strategy.

The exponential backoff pattern with reasonable delay intervals provides good resilience against connection failures.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (3)
app/src/main/java/me/capcom/smsgateway/modules/receiver/ReceiverService.kt (1)

24-30: Consider adding error handling and state management.

The lifecycle methods lack error handling and protection against multiple start/stop calls.

Consider adding basic state management and error handling:

+private var isStarted = false
+
 fun start(context: Context) {
+    if (isStarted) return
+    try {
         eventsReceiver.start()
+        isStarted = true
+    } catch (e: Exception) {
+        Log.e("ReceiverService", "Failed to start events receiver", e)
+        throw e
+    }
 }

 fun stop(context: Context) {
+    if (!isStarted) return
+    try {
         eventsReceiver.stop()
+        isStarted = false
+    } catch (e: Exception) {
+        Log.e("ReceiverService", "Failed to stop events receiver", e)
+    }
 }
app/src/main/java/me/capcom/smsgateway/modules/receiver/events/MessagesExportRequestedEvent.kt (1)

7-17: Consider using java.time API instead of Date

The Date class is legacy and has various issues. Consider using java.time.Instant or java.time.LocalDateTime for better date/time handling.

-import java.util.Date
+import java.time.Instant

 class MessagesExportRequestedEvent(
-    val since: Date,
-    val until: Date,
+    val since: Instant,
+    val until: Instant,
 ) : AppEvent(NAME) {
     data class Payload(
         @SerializedName("since")
-        val since: Date,
+        val since: Instant,
         @SerializedName("until")
-        val until: Date,
+        val until: Instant,
     )
app/src/main/java/me/capcom/smsgateway/services/PushService.kt (1)

31-44: Consider adding debug logging for received events

For better observability, consider logging the routed events.

 override fun onMessageReceived(message: RemoteMessage) {
     try {
         Log.d(this.javaClass.name, message.data.toString())

         val event = message.data["event"]?.let { ExternalEventType.valueOf(it) }
             ?: ExternalEventType.MessageEnqueued
         val data = message.data["data"]
+        
+        Log.d(this.javaClass.name, "Routing event: $event with data: $data")

         eventsRouter.route(
             ExternalEvent(
                 type = event,
                 data = data,
             )
         )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6e34d8c and b58170d.

📒 Files selected for processing (18)
  • app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEventType.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/EventsReceiver.kt (3 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/MessageEnqueuedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/SettingsUpdatedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/WebhooksUpdatedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/services/SSEForegroundService.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/workers/WebhooksUpdateWorker.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/orchestrator/EventsRouter.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/orchestrator/Module.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/orchestrator/OrchestratorService.kt (3 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/push/events/PushMessageEnqueuedEvent.kt (0 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/push/payloads/MessagesExportRequestedPayload.kt (0 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/receiver/EventsReceiver.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/receiver/ReceiverService.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/receiver/events/MessagesExportRequestedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/services/PushService.kt (2 hunks)
💤 Files with no reviewable changes (2)
  • app/src/main/java/me/capcom/smsgateway/modules/push/payloads/MessagesExportRequestedPayload.kt
  • app/src/main/java/me/capcom/smsgateway/modules/push/events/PushMessageEnqueuedEvent.kt
✅ Files skipped from review due to trivial changes (6)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/workers/WebhooksUpdateWorker.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/WebhooksUpdatedEvent.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/SettingsUpdatedEvent.kt
  • app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEvent.kt
  • app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEventType.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/MessageEnqueuedEvent.kt
🚧 Files skipped from review as they are similar to previous changes (2)
  • app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/services/SSEForegroundService.kt
🔇 Additional comments (9)
app/src/main/java/me/capcom/smsgateway/modules/orchestrator/Module.kt (1)

8-8: LGTM!

The addition of EventsRouter as a singleton follows the correct Koin DI pattern and aligns with the new event routing architecture.

app/src/main/java/me/capcom/smsgateway/modules/orchestrator/OrchestratorService.kt (2)

21-21: LGTM!

The addition of ReceiverService as a dependency follows the correct constructor injection pattern.


58-58: LGTM!

The service stop order follows the reverse startup sequence, which is the correct lifecycle management pattern.

app/src/main/java/me/capcom/smsgateway/modules/gateway/EventsReceiver.kt (4)

9-11: LGTM!

The import updates correctly reflect the new event classes that replace the old push event architecture.


14-15: LGTM!

The worker imports are correctly updated to match the new worker classes.


27-28: LGTM!

The transition from PushMessageEnqueuedEvent to MessageEnqueuedEvent is correctly implemented while maintaining the same functional behavior.


61-81: LGTM!

The new event collectors for WebhooksUpdatedEvent and SettingsUpdatedEvent follow the established patterns:

  • Consistent logging and event handling structure
  • Proper settings validation before processing
  • Correct worker invocation with dependency injection
app/src/main/java/me/capcom/smsgateway/modules/receiver/ReceiverService.kt (1)

22-22: LGTM!

Lazy initialization of eventsReceiver is appropriate for performance optimization.

app/src/main/java/me/capcom/smsgateway/modules/receiver/EventsReceiver.kt (1)

1-30: LGTM!

The EventsReceiver implementation follows established patterns correctly:

  • Proper async event handling with coroutineScope and launch
  • Consistent logging structure matching other EventsReceiver classes
  • Correct dependency injection using Koin
  • Clean event delegation to the service layer

The inline use of get() for context dependency is consistent with patterns used elsewhere in the codebase.

@capcom6 capcom6 force-pushed the feature/sse-events branch from 8c56016 to 4c326ad Compare August 2, 2025 02:11
@capcom6
Copy link
Owner Author

capcom6 commented Aug 3, 2025

@coderabbitai full review

Copy link

coderabbitai bot commented Aug 3, 2025

✅ Actions performed

Full review triggered.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (6)
app/src/main/java/me/capcom/smsgateway/modules/orchestrator/OrchestratorService.kt (1)

39-53: ReceiverService lifecycle partially addressed but cleanup still needed.

While receiverService.start() is now inside the try-catch block (addressing part of the previous concern), there's still no cleanup logic if the exception handling causes an early return (line 49). The ReceiverService could remain running if other foreground services fail to start.

Consider adding cleanup logic for early returns:

         } catch (e: Throwable) {
             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
                 && e is ForegroundServiceStartNotAllowedException
             ) {
+                receiverService.stop(context)
                 logsSvc.insert(
                     LogEntry.Priority.WARN,
                     MODULE_NAME,
app/src/main/java/me/capcom/smsgateway/modules/orchestrator/EventsRouter.kt (3)

15-18: Add lifecycle management for the coroutine scope

The EventsRouter creates a coroutine scope but never cancels it. This could lead to memory leaks if the router instance is no longer needed but coroutines are still running.


21-45: Remove redundant nested coroutine launches

The outer launch already runs on the IO dispatcher, so the nested launches for each event type are redundant and create unnecessary coroutines.


33-38: Handle null data gracefully instead of using requireNotNull

Using requireNotNull will throw an IllegalArgumentException if event.data is null, which could crash the app. Consider handling this case more gracefully.

app/src/main/java/me/capcom/smsgateway/modules/receiver/events/MessagesExportRequestedEvent.kt (1)

23-26: Add error handling and validation for payload parsing

The withPayload method could throw exceptions during JSON parsing and doesn't validate that the date range is valid (since <= until).

app/src/main/java/me/capcom/smsgateway/services/PushService.kt (1)

30-31: valueOf safety issue remains unaddressed.

The previous concern about ExternalEventType.valueOf(it) potentially throwing IllegalArgumentException for invalid event strings still exists.

-val event = message.data["event"]?.let { ExternalEventType.valueOf(it) }
-    ?: ExternalEventType.MessageEnqueued
+val event = message.data["event"]?.let { eventString ->
+    try {
+        ExternalEventType.valueOf(eventString)
+    } catch (e: IllegalArgumentException) {
+        Log.w(this.javaClass.name, "Unknown event type: $eventString, defaulting to MessageEnqueued")
+        ExternalEventType.MessageEnqueued
+    }
+} ?: ExternalEventType.MessageEnqueued
🧹 Nitpick comments (3)
app/src/main/java/me/capcom/smsgateway/modules/receiver/ReceiverService.kt (1)

24-30: Consider whether Context parameter is needed.

The start() and stop() methods accept a Context parameter but don't use it. While this maintains consistency with other service interfaces in the orchestrator, consider if this parameter will be needed for future functionality or if it can be removed for clarity.

If the Context parameter isn't planned for future use, consider simplifying:

-    fun start(context: Context) {
+    fun start() {
         eventsReceiver.start()
     }

-    fun stop(context: Context) {
+    fun stop() {
         eventsReceiver.stop()
     }

Alternatively, add a comment indicating the parameter is reserved for future use.

app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt (1)

22-24: Consider adding connection timeout to OkHttpClient

While the read timeout is set to 1 hour for SSE, consider adding a connection timeout for initial connection establishment.

    private val client = OkHttpClient.Builder()
+       .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(1, TimeUnit.HOURS)
        .build()
app/src/main/java/me/capcom/smsgateway/modules/gateway/services/SSEForegroundService.kt (1)

122-122: Consider using STOP_FOREGROUND_REMOVE for better cleanup.

Using stopForeground(true) is deprecated. Consider using the newer API for better clarity.

-stopForeground(true)
+if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
+    stopForeground(STOP_FOREGROUND_REMOVE)
+} else {
+    @Suppress("DEPRECATION")
+    stopForeground(true)
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 404dd29 and 4c326ad.

⛔ Files ignored due to path filters (5)
  • app/src/main/res/drawable-hdpi/notif_realtime_events.png is excluded by !**/*.png
  • app/src/main/res/drawable-mdpi/notif_realtime_events.png is excluded by !**/*.png
  • app/src/main/res/drawable-xhdpi/notif_realtime_events.png is excluded by !**/*.png
  • app/src/main/res/drawable-xxhdpi/notif_realtime_events.png is excluded by !**/*.png
  • app/src/main/res/drawable-xxxhdpi/notif_realtime_events.png is excluded by !**/*.png
📒 Files selected for processing (25)
  • app/build.gradle (2 hunks)
  • app/src/main/AndroidManifest.xml (2 hunks)
  • app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/helpers/SettingsHelper.kt (0 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEventType.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/EventsReceiver.kt (3 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewayService.kt (5 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewaySettings.kt (2 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/MessageEnqueuedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/SettingsUpdatedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/events/WebhooksUpdatedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/services/SSEForegroundService.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/gateway/workers/WebhooksUpdateWorker.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/notifications/NotificationsService.kt (2 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/orchestrator/EventsRouter.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/orchestrator/Module.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/orchestrator/OrchestratorService.kt (3 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/push/events/PushMessageEnqueuedEvent.kt (0 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/push/payloads/MessagesExportRequestedPayload.kt (0 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/receiver/EventsReceiver.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/receiver/ReceiverService.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/modules/receiver/events/MessagesExportRequestedEvent.kt (1 hunks)
  • app/src/main/java/me/capcom/smsgateway/services/PushService.kt (3 hunks)
  • app/src/main/res/values/strings.xml (1 hunks)
💤 Files with no reviewable changes (3)
  • app/src/main/java/me/capcom/smsgateway/helpers/SettingsHelper.kt
  • app/src/main/java/me/capcom/smsgateway/modules/push/events/PushMessageEnqueuedEvent.kt
  • app/src/main/java/me/capcom/smsgateway/modules/push/payloads/MessagesExportRequestedPayload.kt
🔇 Additional comments (31)
app/build.gradle (2)

60-60: LGTM - OkHttp version variable added.

The addition of the okhttp_version variable follows the existing pattern for dependency version management.


84-86: Verify OkHttp version alignment with Ktor client

The POM inspection didn’t surface a direct OkHttp dependency for io.ktor:ktor-client-okhttp:2.2.4. Please manually confirm which OkHttp version that artifact brings in (via its POM or BOM) and ensure your $okhttp_version (currently 4.10.0) matches it to avoid classpath conflicts.

• File: app/build.gradle, lines 84–86

implementation("com.squareup.okhttp3:okhttp:$okhttp_version")
implementation("com.squareup.okhttp3:okhttp-sse:$okhttp_version")
app/src/main/java/me/capcom/smsgateway/modules/notifications/NotificationsService.kt (2)

95-95: LGTM - Notification ID added correctly.

The new notification ID follows the existing sequential pattern and integrates well with the notification system.


27-27: Drawable Resource Exists

Verified that notif_realtime_events.png is present under app/src/main/res/drawable-hdpi, drawable-mdpi, drawable-xhdpi, drawable-xxhdpi, and drawable-xxxhdpi. No further action required.

app/src/main/res/values/strings.xml (1)

122-122: LGTM - String resource added correctly.

The new string resource follows the naming convention and provides clear user feedback for the SSE service notification.

app/src/main/java/me/capcom/smsgateway/modules/orchestrator/Module.kt (1)

8-8: LGTM - EventsRouter singleton registration added correctly.

The EventsRouter is properly registered as a singleton following the established pattern and Koin best practices.

app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEventType.kt (2)

1-1: LGTM - Package restructuring improves organization.

Moving from push to events package better reflects the broader usage of this enum for both push and SSE events.


5-17: No remaining references to the old Event class found – all Event-suffixed types are distinct classes.
The grep only surfaced usages of DeviceRegisteredEvent, WebHookEvent, SmsEventPayload, etc., which are unrelated to the renamed ExternalEventType. All imports from me.capcom.smsgateway.modules.push.Event have been removed.

app/src/main/java/me/capcom/smsgateway/modules/events/ExternalEvent.kt (1)

3-6: LGTM! Clean and well-designed data class.

The ExternalEvent data class provides a clear contract for external events with appropriate type safety through the ExternalEventType enum and flexibility with the nullable data property. This design supports the new SSE event architecture effectively.

app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewaySettings.kt (2)

22-24: LGTM! Follows established patterns.

The fcmToken property implementation is consistent with other properties in the class, using the same getter/setter pattern with KeyValueStorage. The nullable type is appropriate for FCM tokens that may not always be available.


39-39: LGTM! Consistent constant naming.

The FCM_TOKEN constant follows the established naming convention used by other storage keys in the class.

app/src/main/java/me/capcom/smsgateway/modules/gateway/workers/WebhooksUpdateWorker.kt (1)

49-49: LGTM! Improved naming consistency.

Changing the worker name from "CloudUpdateWorker" to "WebhooksUpdateWorker" aligns the identifier with the class name and better reflects the worker's specific purpose of handling webhook updates.

app/src/main/java/me/capcom/smsgateway/modules/gateway/events/SettingsUpdatedEvent.kt (1)

5-9: LGTM! Follows established event class pattern.

The SettingsUpdatedEvent class correctly extends AppEvent and follows the standard pattern with a NAME constant. The implementation is clean and appropriate for a simple event notification.

app/src/main/java/me/capcom/smsgateway/modules/gateway/events/MessageEnqueuedEvent.kt (1)

5-8: LGTM! Consistent event class implementation.

The MessageEnqueuedEvent class follows the same established pattern as other event classes, extending AppEvent with a proper NAME constant. This supports the migration from push-based to SSE-based event architecture.

app/src/main/java/me/capcom/smsgateway/modules/gateway/events/WebhooksUpdatedEvent.kt (1)

1-9: LGTM! Clean event class implementation.

The event class follows a consistent pattern with the companion object containing the event name constant. This approach ensures type safety and consistency across the event system.

app/src/main/java/me/capcom/smsgateway/modules/gateway/EventsReceiver.kt (3)

9-17: LGTM! Import updates align with new event architecture.

The imports correctly reflect the transition from push-based to SSE-based event handling with the new event classes and SSEForegroundService.


29-30: Good update to use the new MessageEnqueuedEvent.

The change from PushMessageEnqueuedEvent to MessageEnqueuedEvent aligns with the refactoring away from push-specific event handling.


63-95: Well-structured new event collectors with appropriate conditional logic.

The new collectors for WebhooksUpdatedEvent, SettingsUpdatedEvent, and DeviceRegisteredEvent follow a consistent pattern. The conditional logic for starting SSEForegroundService (lines 91-93) is particularly well thought out - only starting when gateway is enabled and FCM token is null, which makes sense for fallback SSE connectivity.

app/src/main/AndroidManifest.xml (1)

30-34: ✅ Previous security and API compliance issues have been resolved.

The service declaration now correctly includes:

  • android:exported="false" for security (prevents external access)
  • android:foregroundServiceType="dataSync" for API 29+ compliance

This addresses the concerns raised in previous reviews.

app/src/main/java/me/capcom/smsgateway/modules/orchestrator/OrchestratorService.kt (2)

21-21: Good addition of ReceiverService dependency.

The ReceiverService integration follows the established pattern for service dependencies in the orchestrator.


57-57: Proper service shutdown order maintained.

The ReceiverService is stopped first, which is appropriate for the service lifecycle management.

app/src/main/java/me/capcom/smsgateway/modules/receiver/ReceiverService.kt (1)

22-22: Good use of lazy initialization for EventsReceiver.

The lazy initialization ensures the EventsReceiver is only created when needed, which is efficient for lifecycle management.

app/src/main/java/me/capcom/smsgateway/modules/gateway/GatewayService.kt (1)

56-56: Good improvements to lifecycle management and push token handling

The changes improve the code by:

  • Adding proper SSE service lifecycle management
  • Making push token handling more robust with nullable types
  • Ensuring FCM token is always stored after registration
  • Simplifying the update logic

Also applies to: 111-111, 136-136, 158-174

app/src/main/java/me/capcom/smsgateway/helpers/SSEManager.kt (1)

89-97: Good implementation of disconnect with proper cleanup

The disconnect method properly handles:

  • Setting the disconnecting flag to prevent reconnection attempts
  • Cancelling the event source
  • Cancelling all coroutine children
app/src/main/java/me/capcom/smsgateway/modules/gateway/services/SSEForegroundService.kt (4)

45-47: Null safety improvement implemented correctly.

The previous concern about using requireNotNull without proper error handling has been addressed. The custom error message provides clear context for debugging.


72-77: Lock acquisition safety checks properly implemented.

The safety checks for wake lock and WiFi lock acquisition prevent potential exceptions from acquiring already-held locks.


94-96: onBind method correctly implemented.

The method now properly returns null instead of throwing a TODO exception, which is appropriate for a foreground service not designed for binding.


116-121: Lock release safety checks properly implemented.

The isHeld checks before releasing locks prevent potential exceptions from releasing already-released locks.

app/src/main/java/me/capcom/smsgateway/services/PushService.kt (3)

43-49: Exception handling improvement implemented correctly.

The previous concern about using printStackTrace() has been properly addressed with structured logging using both Android Log and LogsService.


36-41: Clean refactoring to centralized event routing.

The migration from inline event handling to using EventsRouter improves code organization and maintainability. The routing approach provides better separation of concerns.


62-87: Firebase token handling simplified appropriately.

The token retrieval callback was streamlined while maintaining proper error logging and worker integration.

@capcom6 capcom6 force-pushed the feature/sse-events branch from 4c326ad to 0a94d1e Compare August 3, 2025 13:22
@capcom6 capcom6 marked this pull request as ready for review August 4, 2025 12:36
Copy link
Contributor

github-actions bot commented Aug 4, 2025

🤖 Pull request artifacts

file commit
app-release.apk 0a94d1e
app-release.aab 0a94d1e

@capcom6 capcom6 merged commit 09f9eb9 into master Aug 6, 2025
5 checks passed
@capcom6 capcom6 deleted the feature/sse-events branch August 6, 2025 12:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant